package com.zrx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrx.constants.SystemConstants;
import com.zrx.domain.ResponseResult;
import com.zrx.domain.dto.AddArticleDto;
import com.zrx.domain.dto.ArticleListDto;
import com.zrx.domain.entity.Article;
import com.zrx.domain.entity.ArticleTag;
import com.zrx.domain.entity.Category;
import com.zrx.domain.entity.Tag;
import com.zrx.domain.vo.ArticleDedailVo;
import com.zrx.domain.vo.ArticlePageListVo;
import com.zrx.domain.vo.HotArticleVo;
import com.zrx.domain.vo.PageVo;
import com.zrx.mapper.ArticleMapper;
import com.zrx.service.ArticleService;
import com.zrx.service.ArticleTagService;
import com.zrx.service.CategoryService;
import com.zrx.utils.BeanCopyUtils;
import com.zrx.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 张荣欣
 * @create ：2022/9/14  17:18
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleTagService articleTagService;

    //查询热门文章
    @Override
    public ResponseResult hotArticleList() {

        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //正式文章
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //浏览量序排序
        queryWrapper.orderByDesc(Article::getViewCount);
        //最多查询10条
        Page<Article> page = new Page(1, 10);
        page(page, queryWrapper);

        List<Article> articles = page.getRecords();

        articles.forEach(article -> {
            //从redis 获取viewCount 浏览量
            Integer viewCount = redisCache.getCacheMapValue("article:viewCount", article.getId().toString());
            article.setViewCount(viewCount.longValue());
        });

//        List<HotArticleVo> articleVos = new ArrayList<>();
//        //bean拷贝
//        for (Article article : articles) {
//            HotArticleVo vo = new HotArticleVo();
//            BeanUtils.copyProperties(article,vo);
//            articleVos.add(vo);
//        }

        List<HotArticleVo> vs = BeanCopyUtils.copyBeanList(articles, HotArticleVo.class);

        return ResponseResult.okResult(vs);
    }

    @Override
    public ResponseResult hotHouArticleList() {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //正式文章
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //浏览量序排序
        queryWrapper.orderByDesc(Article::getViewCount);
        //最多查询10条
        Page<Article> page = new Page(1, 10);
        page(page, queryWrapper);

        List<Article> articles = page.getRecords();

//        articles.forEach(article -> {
//            //从redis 获取viewCount 浏览量
//            Integer viewCount = redisCache.getCacheMapValue("article:viewCount", article.getId().toString());
//            article.setViewCount(viewCount.longValue());
//        });

//        List<HotArticleVo> articleVos = new ArrayList<>();
//        //bean拷贝
//        for (Article article : articles) {
//            HotArticleVo vo = new HotArticleVo();
//            BeanUtils.copyProperties(article,vo);
//            articleVos.add(vo);
//        }

        List<HotArticleVo> vs = BeanCopyUtils.copyBeanList(articles, HotArticleVo.class);





        return ResponseResult.okResult(vs);
    }

    /**
     * 前台分页查询文字
     *
     * @param pageNum
     * @param pageSize
     * @param categoryId
     * @return
     */
    @Override
    public ResponseResult articlePageList(Integer pageNum, Integer pageSize, Long categoryId) {
        //查询条件
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 如果有  categoryId 就要 查询时要和传入的相同
        lambdaQueryWrapper.eq(Objects.nonNull(categoryId) && categoryId > 0, Article::getCategoryId, categoryId);

        // 状态 正式发布
        lambdaQueryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //对 isTop 进行降序排序
        lambdaQueryWrapper.orderByDesc(Article::getIsTop);


        //分页查询
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page, lambdaQueryWrapper);

        //categoryId 去查询 categoryName
        List<Article> articles = page.getRecords();

        articles.forEach(article -> {
            //从redis 获取viewCount 浏览量
            Integer viewCount = redisCache.getCacheMapValue("article:viewCount", article.getId().toString());
            article.setViewCount(viewCount.longValue());
        });


        //for 循环
//        for (Article article : articles) {
//            Category category = categoryService.getById(article.getCategoryId());
//            article.setCategoryName(category.getName());
//        }

        //获取分类id 查询分类信息 获取分类名称
        //把分类名 设置给articles
        articles.stream()
                .map(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName()))
                .collect(Collectors.toList());


        //封装
        List<ArticlePageListVo> articlePageListVos = BeanCopyUtils.copyBeanList(page.getRecords(), ArticlePageListVo.class);

        PageVo pageVo = new PageVo(articlePageListVos, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    /**
     * 查询文章内容
     *
     * @return
     */
    @Override
    public ResponseResult getarticleDetail(Long id) {
        //根据id查询文章
        Article article = getById(id);
        //从redis 获取viewCount 浏览量
        Integer viewCount = redisCache.getCacheMapValue("article:viewCount", id.toString());
        article.setViewCount(viewCount.longValue());
        //转换VO
        ArticleDedailVo articleDedailVo = BeanCopyUtils.copyBean(article, ArticleDedailVo.class);
        //根据分类id查询分类名
        Category category = categoryService.getById(articleDedailVo.getCategoryId());
        if (category != null) {
            articleDedailVo.setCategoryName(category.getName());
        }
        //封装相应
        return ResponseResult.okResult(articleDedailVo);
    }

    /**
     * 更新redis 浏览记录
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult updateViewCount(Long id) {

        redisCache.incrementCacheMapValue("article:viewCount", id.toString(), 1);
        return ResponseResult.okResult();
    }

    /**
     * 添加文章
     *
     * @param addArticleDto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult add(AddArticleDto addArticleDto) {
        //添加博客
        Article article = BeanCopyUtils.copyBean(addArticleDto, Article.class);
        save(article);

        List<ArticleTag> articleTags = addArticleDto.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());
        //添加博客和标签的关联
        articleTagService.saveBatch(articleTags);
        return ResponseResult.okResult();
    }

    /**
     * 分页查询文章
     *
     * @param pageNum
     * @param pageSize
     * @param articleListDto
     * @return
     */
    @Override
    public ResponseResult<PageVo> pageArticleList(Integer pageNum, Integer pageSize, ArticleListDto articleListDto) {
        //分页查询
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(articleListDto.getTitle()), Article::getTitle, articleListDto.getTitle());
        queryWrapper.like(StringUtils.hasText(articleListDto.getSummary()), Article::getSummary, articleListDto.getSummary());
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapper);

        //封装数据
        PageVo pageVo = new PageVo(page.getRecords(), page.getTotal());


        return ResponseResult.okResult(pageVo);

    }

    /**
     * 根据id查询文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult getByIdOneArticle(Long id) {
        Article article = getById(id);
        AddArticleDto addArticleDto = BeanCopyUtils.copyBean(article, AddArticleDto.class);
        List<Long> tags = articleTagService.list(new LambdaQueryWrapper<ArticleTag>().eq(ArticleTag::getArticleId, id))
                .stream().map(articleTag -> articleTag.getTagId()).collect(Collectors.toList());
        addArticleDto.setTags(tags);
        return ResponseResult.okResult(addArticleDto);
    }

    /**
     * 修改文章
     * @param addArticleDto
     * @return
     */
    @Override
    public ResponseResult updateArticle(AddArticleDto addArticleDto) {
        //修改博客
        Article article = BeanCopyUtils.copyBean(addArticleDto, Article.class);
        updateById(article);
        //删除原有的 标签和博客的关联
        LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
        articleTagLambdaQueryWrapper.eq(ArticleTag::getArticleId,article.getId());
        articleTagService.remove(articleTagLambdaQueryWrapper);
        //添加新的博客和标签的关联信息
        List<ArticleTag> articleTags = addArticleDto.getTags().stream()
                .map(tagId -> new ArticleTag(addArticleDto.getId(), tagId))
                .collect(Collectors.toList());
        articleTagService.saveBatch(articleTags);

        return null;
    }


}
